import DialogBox from "@/assets/js/DialogBox";
import FormCustomView from "@/views/modules/form/core/formComponent/FormCustomView";
import {Util,TabOpen,App} from "@lowcode/jpaas-common-lib";
import DialogView from "@/layouts/DialogView";
import BpmInstApi from "@/api/bpm/core/bpmInst";
import sysAppApi from "@/api/system/core/sysApp";
import FormDesignApi from '@/api/form/core/formDesign'

export default {
    mixins:[TabOpen,App],
    props: ["secondEdit"],
    created(){
        if(!this.$bus.instance){

            this.$bus.on("formOpenEvent",(obj)=>{
                this.handFormOpen(obj);
            });

            this.$bus.on("bpmInstDetailEvent",(obj)=>{
                this.handBpmInstDetail(obj);
            });

            //处理表单导航事件。
            this.handFormNavEvent();
            //列表按钮点击事件
            this.handListButtonEvent();
            //列表预览事件
            this.handListPreviewEvent();

            this.$bus.instance=true;
        }
        this.hasRigthEidtForm();
    },
    methods: {
        getDialogBox() {
            return DialogBox;
        },
        handListButtonEvent(){
            this.$bus.on("listButtonEvent",(obj)=>{
                this.handButtonClick(obj);
            });
        },
        handListPreviewEvent(){
            this.$bus.on("listPreviewEvent",(obj)=>{
                this.handListPreview(obj);
            });
        },
        handListPreview(obj){
            if(!obj){
                return;
            }
            switch (obj.type) {
                case 'openCustom':
                    var baseConf= {
                        "curVm": this,
                        component: FormCustomView,
                        title: this.$ti18('list.formCustom','表单定制','formBoList')+"-"+obj.alias,
                        max:true,
                        "data": {
                            "alias": obj.alias,
                            "params": JSON.stringify(obj.params)
                        },
                        cancel:()=>{
                            if (obj.destroy) {
                                let func=obj.destroy.bind(this);
                                func(this);
                            }
                        }
                    };
                    Util.open(baseConf, function (action) {
                        if (obj.destroy) {
                            let func=obj.destroy.bind(this);
                            func(this);
                        }
                    });
                    break
                case 'openStartFlowDialog':
                    var pk=obj.pk;
                    var view="modules/bpm/core/BpmInstStart";
                    var component=require(`@/views/${view}`).default;
                    //传入流程ID和主键。
                    let paramsObj = {menuParams:JSON.stringify({defKey:obj.alias})};
                    if(pk){
                        paramsObj.pkId=pk;
                    }
                    if(obj.formData){
                        paramsObj.formData=obj.formData;
                    }
                    var baseConf = {
                        component: component,
                        data: paramsObj,
                        title: this.$ti18('list.startProcess','启动流程','formBoList'),
                        curVm: this,
                        max:true
                    };
                    var self_=this;
                    Util.open(baseConf, function (action, data) {
                        if (action != 'ok') return;
                        if(obj.destroy){
                            obj.destroy(action,data);
                        }else {
                            if (obj.table && obj.table.loadData) {
                                obj.table.loadData();
                            }
                        }
                    });
                    break
                case 'openComponent':
                    DialogBox.openComponent(obj.config, obj.callback);
                    break
                case 'showForm':
                    //{"title":"测试EXCEL导出","alias":"user","pkId":"",
                    // "readOnly":false,"parent":{},"params":{"CREATE_BY_":"1"},
                    // "closeOnSave":true}
                    var readOnly_ = obj.obj.readOnly == 'true' ? true : false;
                    var urlType = readOnly_ ? "Details" : "EditRow";
                    this.showForm({
                        ...obj.obj,
                        isMax:obj.isMax,
                        isShade:obj.isShade,
                        width:obj.width,
                        height:obj.height,
                        urlType: urlType,
                        table:obj.table
                    })
                    break
                case 'openForm':
                    if (!obj.formAlias) {
                        return;
                    }
                    var formAliasObj = JSON.parse(obj.formAlias);
                    var fieldMap_ = obj.fieldMap;

                    if(typeof fieldMap_=="string"){
                        fieldMap_=JSON.parse(obj.fieldMap);
                    }

                    var readOnly_=obj.readOnly;
                    if(typeof readOnly_=="string"){
                        readOnly_ =  obj.readOnly == 'true' ? true : false;
                    }

                    var urlType = readOnly_ ? "Details" : "EditRow";
                    var pkId = "";
                    if (obj.pkField) {
                        pkId = obj.row[obj.pkField];
                    }
                    var self = obj.listVm;
                    var config = {
                        title: formAliasObj.text,
                        curVm: this,
                        data: {
                            alias: formAliasObj.value,
                            pkId: pkId,
                            readOnly: readOnly_,
                            //将表单映射数据提交到表单数据。
                            setInitData(data) {
                                if (obj.row) {
                                    for (var i = 0; i < fieldMap_.length; i++) {
                                        data[fieldMap_[i].destField] = obj.row[fieldMap_[i].srcField];
                                    }
                                }
                                return data;
                            }
                        },
                        max:obj.isMax=='YES',
                        widthHeight:[obj.width + 'px', obj.height + 'px'],
                        shade: obj.isShade=='YES',
                        urlType: urlType,
                    }
                    DialogBox.showForm(config, function (action) {
                        if (obj.callback) {
                            var call = "self." + obj.callback + "(row,self)";
                            eval(call);
                        }
                        self.onRefresh();
                    });
                    break
                case 'showBusSolutionForm':
                    var self=obj.listVm;
                    var readOnly=obj.readOnly;
                    if (obj.obj.readOnly) {
                        readOnly=obj.obj.readOnly ;
                    }
                    var config = {
                        title: self.formBoList.name + '--'+this.$ti18('rxList.newBtn','添加'),
                        curVm: this,
                        data: {
                            alias: obj.obj.value,
                            rowData: obj.rowData,
                            busSolId: obj.obj.value,
                            readOnly: readOnly,
                            //将表单映射数据提交到表单数据。
                            setInitData(data) {
                                if (self.formdata) {
                                    Object.assign(data, self.formdata);
                                }
                                return data;
                            }
                        },
                        max: true
                    }
                    DialogBox.showBusSolutionForm(config, function (action) {
                        if (obj.callback) {
                            var call = "self." + obj.callback + "(row,self)";
                            eval(call);
                        }
                        self.onRefresh();
                    });
                    break
                default:
                    break
            }
        },
        handFormOpen(obj){
            var data={};
            if(obj.settingType=='iframe'){
                data.url=obj.url;
            }else if(obj.settingType=='form'){
                var alias=obj.params.alias;
                var pk=obj.params.pk;
                if(!pk && obj.params.params){
                    pk=obj.params.params.pk;
                }
                var readOnly=obj.params.readOnly;
                var parent=obj.params.parent;
                var params=obj.params.params;
                let _obj = {
                    title:obj.title,
                    alias:alias,
                    pkId:pk,
                    readOnly:readOnly,
                    parent:parent,
                    params:params,
                    destroy:obj.destroy,
                    urlType:'Open',
                    isMax:'YES',
                    isShade:'YES',
                    width:650,
                    height:350,
                    table:obj.table
                }
                this.showForm(_obj);
                return;
            }else if(obj.settingType=='list'){

                DialogBox.dialog(obj.params.params,{...{curVm:this,max:true},...obj.params.config},obj.destroy);
                return;
            }else{
                data.menu={params:obj.params.params};
                data.currentView=() => import(`@/views/${obj.url}`);
            }
            var conf = {
                component: DialogView,
                curVm:this,
                max:true,
                title: obj.title,
                data:data
            };
            Util.open(conf,function (action, data) {
                if(obj.destroy) {
                    obj.destroy(action, data);
                }
            });
        },
        handButtonClick(obj){
            var action=obj.action;
            action=action.charAt(0).toUpperCase() + action.slice(1);
            var self_=this;
            var method="self_.hand" +action +"(obj)";
            eval(method);
        },
        handBpmDetail(obj){
            var record=obj.record;
            this.openInst(record.APP_ID_,record.INST_ID_);
        },
        handAdd(obj){
            let _obj = {
                title:this.$ti18('rxList.newBtn','添加')+"-"+obj.name,
                alias:obj.alias,
                pkId:"",
                readOnly:false,
                parent:obj.parent,
                params:obj.formdata,
                urlType:'Add',
                isMax:obj.isMax,
                isShade:obj.isShade,
                width:obj.width,
                height:obj.height,
                destroy:obj.destroy,
                closeOnSave:true,
                table:obj.table
            }
            this.showForm(_obj);
        },
        handEdit(obj){
            let _obj = {
                title:this.$ti18('rxList.editBtn','编辑')+"-"+obj.name,
                alias:obj.alias,
                pkId:obj.pk,
                readOnly:false,
                parent:null,
                urlType:'Edit',
                isMax:obj.isMax,
                isShade:obj.isShade,
                width:obj.width,
                height:obj.height,
                destroy:obj.destroy,
                closeOnSave:true,
                table:obj.table
            }
            this.showForm(_obj);
        },
        handDetail(obj){
            let _obj = {
                title:obj.name +"-"+this.$ti18('rxList.detailBtn','明细'),
                alias:obj.alias,
                pkId:obj.pk,
                readOnly:true,
                parent:null,
                urlType:'Details',
                isMax:obj.isMax,
                isShade:obj.isShade,
                width:obj.width,
                height:obj.height,
                table:obj.table
            }
            this.showForm(_obj);
        },
        showForm(obj) {
            if(!obj.alias){
                return;
            }
            if (!obj.readOnly) {
                obj.readOnly = false;
            }
            var data={alias: obj.alias, pkId: obj.pkId, readOnly: obj.readOnly, parent: obj.parent,closeOnSave:obj.closeOnSave,params:obj.params};
            if(obj.params){
                data.setInitData=function(data){
                    Object.assign(data,obj.bindData || obj.params);
                    return data;
                }
            }

            var self_ = this;
            DialogBox.showForm({
                title:obj.title,
                curVm: self_,
                data: data,
                max:obj.isMax=='YES',
                widthHeight:[obj.width + 'px', obj.height + 'px'],
                shade: obj.isShade=='YES',
                urlType:obj.urlType,
                open:obj.open //在新页面的模式下 打开表单的方式  open：‘window’弹窗打开；
            }, function (action,data) {
                if(obj.destroy){
                    obj.destroy(action,data);
                }
                else{
                    if(obj.table && obj.table.loadData){
                        obj.table.loadData();
                    }
                }
            });
        },
        handBpmInstDetail(item){
            this.openDetail(item.appId,item.id);
        },
        loadView  (view)  { // 路由懒加载
            return () => import(`@/views/${view}`)
        },
        /*
        {
            "id": "eevcijy411770",
            "name": "客户信息",
            "name_display": "客户信息<span style='color: #df8a13;margin-left:20px'>已配</span>",
            "params": {
                "type": "form",
                "listComponent": "",
                "listParams": [],
                "formComponent": "{\"text\":\"客户信息\",\"value\":\"customerinfo\"}",
                "paramMapType": "pk",
                "fieldPk": "ID_",
                "fieldPkValMode": "single",
                "fieldMap": [],
                "customComponent": ""
            },
            "parentId": "0",
            "name_editable": true,
            "serial": 1
        }*/
        handFormNavEvent(){
            this.$bus.on('form-nav-event', (settingObj, formNavCtl) => {
                var setting=settingObj.params;
                var component= this.getComponent(setting);
                formNavCtl.setComponent(component,setting)
            })
        } ,
        getComponent(obj){
            var component="";
            if(obj.type=="form"){
                component=  "modules/form/core/FormSolutionComponent.vue";
            }
            else if(obj.type=="list"){
                component=  "modules/form/core/FormBoListPreview.vue";
            }
            else{
                component= obj.customComponent;
            }

            return this.loadView(component);
        },
        encryptInstId(instId,callback){
            BpmInstApi.getBpmInstEncrypt(instId).then(res=>{
                if(!res.success){
                    this.$message.warn(res.message);
                    return;
                }
                callback(res.data);
            })
        },
        /**
         * 打开流程实例页面
         * <pre>
         *     1.审批页面
         *     2.流程实例
         * </pre>
         * @param instId
         * @param taskType
         */
        async openInst(appId,instId){
            var self=this;
            var url=null;
            if(appId){
                var  res= await sysAppApi.get(appId);
                let app= res.data;
                if("1"==app.menuNavType ||"2"==app.menuNavType){
                    url=app.path;
                }
            }

            self.encryptInstId(instId,function(encryptInstId){
                appId=encryptInstId.appId;
                encryptInstId=encryptInstId.instId;
                if(url){
                    var rooturl=url+"/bpm/workbench/openDoc/"+encryptInstId;
                    window.open(rooturl,"_blank" );
                }else {
                    let obj=self.$router.resolve({
                        name:'openDoc',
                        params:{instId:encryptInstId},
                        query:{appId:appId}
                    });
                    window.open(obj.href,"_blank" );
                }
            })
        },
        /**
         * 打开明细
         * @param instId
         */
        async openDetail(appId,instId){
            var self=this;
            var url=null;
            if(appId){
                var  res= await sysAppApi.get(appId);
                let app= res.data;
                if("1"==app.menuNavType ||"2"==app.menuNavType){
                    url=app.path;
                }
            }
            self.encryptInstId(instId,function(encryptInstId){
                appId=encryptInstId.appId;
                encryptInstId=encryptInstId.instId;
                if(url){
                    var rooturl=url+"/bpm/workbench/openDoc/"+encryptInstId+"?action=detail";
                    window.open(rooturl,"_blank" );
                }else {
                    let obj=self.$router.resolve({
                        name:'openDoc',
                        params:{instId:encryptInstId},
                        query:{action:"detail",appId:appId}
                    });
                    window.open(obj.href,"_blank" );
                }
            })
        },
        /**
         * 新页签打开表单方案
         */
        openNewTabForm(obj){
            if(!obj.alias){
                return;
            }
            if (!obj.readOnly) {
                obj.readOnly = false;
            }
            var data={formAlias: obj.alias, pkId: obj.pkId, readOnly: obj.readOnly, parent: obj.parent,closeOnSave:obj.closeOnSave,params:obj.params};
            if(obj.params){
                data.setInitData=function(data){
                    Object.assign(data,obj.bindData || obj.params);
                    return data;
                }
            }
            let config = {
                title:obj.title, //页面名称 必填
                key:"openNewTabForm",//页面路由name  必填
                params:data,
            }
            this.openTabs(config);
        },
        editFormBoList(){
            var action="boList";
            if (this.formBoList.isTreeDlg == "YES") {
                action="boListTree";
            };
            let appId=this.curApp.appId||'';
            let ctxPath=process.env.VUE_APP_ADMIN_FRONT;
            let isDialog= this.formBoList.isDialog;
            let href=ctxPath+"/form/workbench/editForm/"+this.formBoList.id+"?appId="+appId+"&action="+action+"&isDialog="+isDialog;
            window.open(href,"_blank" );
        },
        editFormDialog() {
            var component="FormBoListEdit";
            if (this.formBoList.isTreeDlg == "YES") {
                component="FormBoListTreeEdit";
            }
            this.$router.push({
                name: component,
                query: {
                    pkId: this.formBoList.id,
                    isDialog: "YES"
                }
            })
        },
        hasRigthEidtForm(){
            if(!this.formBoList || !this.formBoList.id || "NO"==this.secondEdit){
                return;
            }
            var self_=this;
            var parma={
                appId:this.curApp.appId,
                params:{
                    formBoList:this.formBoList.id
                }
            }
            FormDesignApi.checkCanChange(parma).then(res=>{
                if(res){
                    self_.canEditBoList=res.formBoList;
                }
            });
        },
    }
}